import wtforms
from wtforms.validators import Email, Length, EqualTo
from models import UserModel, EmailCaptchaModel, SpeciesModel, SiteModel, ProjectsModel
from exts import db
from flask import g

#Form：验证前端传来的数据是否符合要求
class RegisterForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message="邮箱格式错误")])
    captcha = wtforms.StringField(validators=[Length(min=4,max=4,message="验证码格式错误")])
    username = wtforms.StringField(validators=[Length(min=3,max=20,message="用户名长度不合规")])
    password = wtforms.StringField(validators=[Length(min=6,max=20,message="密码长度不合规")])
    password_confirm = wtforms.StringField(validators=[EqualTo("password", message="两次输入的密码不一致")])

    # 自定义验证：
    # 1、邮箱是否已被注册
    def validate_email(self, filed):
        email = filed.data
        user = UserModel.query.filter_by(email=email).first()
        if user:
            raise wtforms.ValidationError(message="该邮箱已被注册，不可重复注册！")

    # 2、验证码是否正确
    def validate_captcha(self, field):
        captcha = field.data
        email = self.email.data
        captcha_model = EmailCaptchaModel.query.filter_by(email=email, captcha=captcha).first()
        if not captcha_model:
            raise wtforms.ValidationError(message="验证码填写错误！")
        # todo:可以删掉captcha_model，网站的性能瓶颈就是和数据库的数据交换
        else:
            db.session.delete(captcha_model)
            db.session.commit()

class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message="邮箱格式错误")])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message="密码格式错误")])

class AddSpecies(wtforms.Form):
    speciesname = wtforms.StringField(validators=[Length(min=1,message='物种名称格式错误')])

    def validate_speciesname(self, field):
        speciesname = field.data
        specie = SpeciesModel.query.filter_by(user_id=g.user.id,speciesname=speciesname).first()
        if specie:
            raise wtforms.ValidationError(message='该物种名称已被使用，不可重复使用！')

class AddSite(wtforms.Form):
    sitename = wtforms.StringField(validators=[Length(min=1,message='站点名称格式错误')])

    def valiedate_sitename(self, field):
        sitename = field.data
        site = SiteModel.query.filter_by(user_id=g.user.id,sitename=sitename).first()
        if site:
            raise wtforms.ValidationError(message='该站点名称已被使用，不可重复使用！')

class AddProjectForm(wtforms.Form):
    projectname = wtforms.StringField(validators=[Length(min=1,message='项目名称长度不合规！')])

    def validate_projectname(self,field):
        projectname = field.data
        project = ProjectsModel.query.filter_by(user_id=g.user.id,projectname=projectname).first()
        if project:
            raise wtforms.ValidationError(message='该项目名称已被使用，不可重复使用！')